package com.hope.bubble.jwt;


import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件名：JwtAuthenticationFilter
 * 创建者：hope
 * 邮箱：1602774287@qq.com
 * 微信：hope4cc
 * 创建时间：2022/10/21-22:06
 * 描述：
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final PathMatcher pathMatcher = new AntPathMatcher();

    /**
     *
     * @param request 客户端的请求
     * @param response 响应
     * @param filterChain 过滤器链
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            if(isProtectedUrl(request)) { //考察一下请求的地址是不是受保护的地址  protectedPaths
//                System.out.println(request.getMethod());
                if(!request.getMethod().equals("OPTIONS")) //获取请求的方法，试探请求不校验
                    request = JwtUtil.validateTokenAndAddUserIdToHeader(request);//如果不是判断一下
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }

        filterChain.doFilter(request, response);
    }

    private boolean isProtectedUrl(HttpServletRequest request) {
        List<String> protectedPaths = new ArrayList<String>();
        //受保护的请求路径
        protectedPaths.add("/ums/user/info");
        protectedPaths.add("/post/create"); //发微博
        protectedPaths.add("/post/update"); //更新微博
        protectedPaths.add("/post/delete/*");//删除微博
        protectedPaths.add("/comment/add_comment"); //发表评论
        protectedPaths.add("/relationship/subscribe/*"); //关注用户
        protectedPaths.add("/relationship/unsubscribe/*"); //取消用户
        protectedPaths.add("/relationship/validate/*");
        boolean bFind = false;
        for( String passedPath : protectedPaths ) {
            //客户端的请求发送过来 从request里得到请求的路径 再根列表的路径对比一下
            bFind = pathMatcher.match(passedPath, request.getServletPath());
            if( bFind ) {
                break;
            }
        }
        return bFind;
    }

}